package cn.tac.framework.dao;


import cn.tac.framework.core.pojo.IGenericBizModel;
import tk.mybatis.mapper.entity.Example;

/**
 * 通用的业务dao基类，用于对mapper的操作做一些封装，以简化编码工作
 *
 * 在{@link GenericDaoSupport}的行为基础上增加了逻辑删除边界
 *
 * @author : tac
 * @since : 2017/7/14
 */
public abstract class GenericBizDaoSupport<E extends IGenericBizModel, PK> extends GenericDaoSupport<E, PK> {
    protected static final String ACTIVE_FIELD_NAME = "active";
    protected static final boolean DEF_ACTIVE = true;       //默认获取active的数据
    protected static final boolean DEF_LOGIC = true;        //默认logic删除

    protected GenericBizMapperSupport<E> bizMapper;

    public GenericBizDaoSupport(GenericMapperSupport<E> bizMapper) {
        super(bizMapper);
    }

    @Override
    public int deleteByPrimaryKey(PK pk) {
        return deleteByPrimaryKey(pk, DEF_LOGIC);
    }

    public int deleteByPrimaryKey(PK pk, boolean logic) {
        if(logic){
            return bizMapper.disableByPrimaryKey(pk);
        }
        return super.deleteByPrimaryKey(pk);
    }

    @Override
    protected void setBoundary(E criteria) {
        criteria.setEnable(DEF_ACTIVE);
    }

    @Override
    protected void setBoundary(Example example) {
//      以租户为边界过滤
        if (example.getOredCriteria().size() == 0) {
            Example.Criteria criteria ;
            criteria = example.createCriteria();
            setBoundaryCriteria(criteria);
        } else {
            for(Example.Criteria criteria : example.getOredCriteria()){
                setBoundaryCriteria(criteria);
            }
        }
    }

    private void setBoundaryCriteria(Example.Criteria criteria) {
        criteria.andEqualTo(ACTIVE_FIELD_NAME, DEF_ACTIVE);
    }
}
